<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>瓦打我</title>
    <link rel="stylesheet" href="./倒计时.css" />
  </head>
  <style></style>
  <body>
    <div class="time">
      <div class="top">
        <button class="hand" data-time="20">20秒</button>
        <button class="hand" data-time="300">工作5分钟</button>
        <button class="hand" data-time="900">休息15分钟</button>
        <button class="hand" data-time="1200">零食20分钟</button>
        <button class="hand" data-time="3600">午饭时间</button>
        <input type="text" placeholder="请输入分钟" />
      </div>
      <div class="mid">
        <p class="up">0:00</p>
        <p class="down"></p>
      </div>
    </div>
  </body>
  <script>
    const buttons = document.querySelectorAll(".hand");
    const input = document.querySelector("input");
    let countdown;

    function timer(seconds) {
      clearInterval(countdown);

      const now = Date.now();
      const then = now + seconds * 1000;

      updateCountdown(seconds);
      countdown = setInterval(() => {
        const secondsLeft = Math.round((then - Date.now()) / 1000);
        if (secondsLeft < 0) {
          clearInterval(countdown);
          return;
        }
        updateCountdown(secondsLeft);
      }, 1000);
    }

    function updateCountdown(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainderSeconds = seconds % 60;
      const display = `${minutes}:${
        remainderSeconds < 10 ? "0" : ""
      }${remainderSeconds}`;
      document.querySelector(".up").textContent = display;

      const localTime = new Date();

      const finalTime = new Date(
        localTime.getTime() + seconds * 1000
      ).toLocaleTimeString();

      document.querySelector(".down").textContent =
        "休息，回来工作时间：" + finalTime.slice(0, -3);
    }

    buttons.forEach((button) => {
      button.addEventListener("click", function () {
        const seconds = parseInt(this.dataset.time);
        timer(seconds);
      });
    });

    input.addEventListener("keydown", function (event) {
      if (event.keyCode === 13) {
        const minutes = parseInt(this.value);
        if (!isNaN(minutes)) {
          timer(minutes * 60);
          this.value = "";
        }
      }
    });
  </script>
</html>
